package com.tourex.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;

import com.tourex.App;
import com.tourex.BaseActivity;
import com.tourex.C;
import com.tourex.C.bean.MyLocationInfo;
import com.tourex.R;
import com.tourex.thirdparty.map.SimpleNaviRouteActivity;
import com.tourex.utils.AnimUtils;
import com.tourex.utils.LogUtils;

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
public class WapActivity extends BaseActivity {

	private WebView webView;

	public static final String E_URL = "e_url";
	public static final String E_TYPE = "e_type";
	public static final String E_PHONE = "e_phone";
	public static final String E_JD = "e_jd";
	public static final String E_WD = "e_wd";
	private String type;
	private String phone;
	private double jd, wd;

	public static void actionStart(Context context, String url) {
		Intent intent = new Intent(context, WapActivity.class);
		intent.putExtra(E_URL, url);
		context.startActivity(intent);
	}

	public static void actionStart(Context context, String url, String type, String phone, double jd, double wd) {
		Intent intent = new Intent(context, WapActivity.class);
		intent.putExtra(E_URL, url);
		intent.putExtra(E_TYPE, type);
		intent.putExtra(E_PHONE, phone);
		intent.putExtra(E_JD, jd);
		intent.putExtra(E_WD, wd);
		context.startActivity(intent);

	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_wap);
		super.onCreate(savedInstanceState);
		type = getIntent().getStringExtra(E_TYPE);
		phone = getIntent().getStringExtra(E_PHONE);
		jd = getIntent().getDoubleExtra(E_JD, 0d);
		wd = getIntent().getDoubleExtra(E_WD, 0d);

		if (C.convention.type_tg.equals(type)) {
			titleLayout.setTitle(R.string.shopping_1);
		} else if (C.convention.type_jd.equals(type)) {
			titleLayout.setTitle(R.string.tourist_attraction);
		} else if (C.convention.type_njl.equals(type)) {
			titleLayout.setTitle(R.string.farm_1);
		} else if (C.convention.type_qz.equals(type)) {
			titleLayout.setTitle(R.string.baby_2);
		} else if (C.convention.type_cz.equals(type)) {
			titleLayout.setTitle(R.string.pick);
		}

		titleLayout.addLeftDrawableMenu(this, R.drawable.ico_back, 25, 25, onBackClickListener);
		titleLayout.removeAllRightMenu();

		if (!TextUtils.isEmpty(phone)) {
			titleLayout.addRightDrawableMenu(this, R.drawable.ico_tel_white, 25, 25, onCallClickListener);
		}
		if (jd != 0d && wd != 0d) {
			titleLayout.addRightDrawableMenu(this, R.drawable.ico_location_1280, 25, 25, onMapClickListener);
		}
		if (C.convention.type_self_info.equals(type)) {
			titleLayout.addRightDrawableMenu(this, R.drawable.ico_home, 25, 25, new OnClickListener() {
				@Override
				public void onClick(View view) {
					MainActivity2.actionStart(WapActivity.this);
					WapActivity.this.finish();
				}
			});
		}

		// WebSettings settings = webView.getSettings();
		// settings.setBuiltInZoomControls(true);
		// settings.setRenderPriority(RenderPriority.HIGH);
		// /** js支持 */
		// settings.setJavaScriptEnabled(true);
		// settings.setSupportZoom(true);
		// settings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		// /** 自适应屏幕 */
		// settings.setUseWideViewPort(true);
		// settings.setLoadWithOverviewMode(true);
		//
		// webView.setWebViewClient(viewClient);
		// webView.setWebChromeClient(chromeClient);
		//
		// String url = getIntent().getStringExtra(E_URL);

		webView = (WebView) this.findViewById(R.id.webview);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.getSettings().setRenderPriority(RenderPriority.HIGH);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setUseWideViewPort(true);
		// webView.addJavascriptInterface(new WebAppInterface(this), "Android");
		webView.addJavascriptInterface(new Handler(), "app");
		webView.loadData("", "text/html", null);
		webView.setWebViewClient(viewClient);
		webView.setWebChromeClient(chromeClient);

		String url = getIntent().getStringExtra(E_URL);
		webView.loadUrl(url);

		if (C.api.homeUrl.equals(url)) {
			MainActivity2.actionStart(this);
			WapActivity.this.finish();
		}

	}

	class Handler {
		public void tel(String data) {
			Uri uri = Uri.parse("tel:" + data);
			Intent intent = new Intent(Intent.ACTION_DIAL, uri);
			startActivity(intent);
		}
	}

	private OnClickListener onCallClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			startAnimation(view, AnimUtils.init().addAlpha(1f, 0.2f, 0, 200, new LinearInterpolator(), Animation.REVERSE).create());

			Uri uri = Uri.parse("tel:" + phone);
			Intent intent = new Intent(Intent.ACTION_DIAL, uri);
			startActivity(intent);
		}
	};

	private OnClickListener onMapClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			startAnimation(view, AnimUtils.init().addAlpha(1f, 0.2f, 0, 200, new LinearInterpolator(), Animation.REVERSE).create());

			MyLocationInfo mli = App.i().mli;
			openActivityMap(mli);
			// openWebViewMap(mli);
		}
	};

	private void openActivityMap(MyLocationInfo mli) {
		// unuse_baidu_RoutePlanActivity.actionStart(WapActivity.this, mli.lng,
		// mli.lat, jd, wd);
		SimpleNaviRouteActivity.actionStart(WapActivity.this, mli.lng, mli.lat, jd, wd);
	}

	@SuppressWarnings("unused")
	private void openWebViewMap(MyLocationInfo mli) {
		String url = C.api.map.replace(C.convention.my_x, String.valueOf(mli.lat)).replace(C.convention.my_y, String.valueOf(mli.lng))
				.replace(C.convention.to_x, String.valueOf(jd)).replace(C.convention.to_y, String.valueOf(wd));
		LogUtils.logd("map url:" + url);
		WapActivity.actionStart(WapActivity.this, url);
	}

	private WebChromeClient chromeClient = new WebChromeClient() {

		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			try {
				final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

				builder.setTitle("对话框").setMessage(message).setPositiveButton("确定", null);

				// 不需要绑定按键事件
				// 屏蔽keycode等于84之类的按键
				builder.setOnKeyListener(new OnKeyListener() {
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						Log.v("onJsAlert", "keyCode==" + keyCode + "event=" + event);
						return true;
					}
				});
				// 禁止响应按back键的事件
				builder.setCancelable(false);
				AlertDialog dialog = builder.create();
				dialog.show();
				result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
			} catch (Exception e) {
				LogUtils.loge("wap on js alert : activity die ? ~");
			}

			return true;
			// return super.onJsAlert(view, url, message, result);
		}

		@Override
		public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
			try {
				final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
				builder.setTitle("对话框").setMessage(message).setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						result.cancel();
					}
				}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						result.cancel();
					}
				});
				builder.setOnCancelListener(new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						result.cancel();
					}
				});

				// 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
				builder.setOnKeyListener(new OnKeyListener() {
					@Override
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						Log.v("onJsConfirm", "keyCode==" + keyCode + "event=" + event);
						return true;
					}
				});
				// 禁止响应按back键的事件
				// builder.setCancelable(false);
				AlertDialog dialog = builder.create();
				dialog.show();
			} catch (Exception e) {
				LogUtils.loge("wap on js alert : activity die ? ~");
			}
			return true;
			// return super.onJsConfirm(view, url, message, result);
		}

		@Override
		public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
			try {
				final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

				builder.setTitle("对话框").setMessage(message);

				final EditText et = new EditText(view.getContext());
				et.setSingleLine();
				et.setText(defaultValue);
				builder.setView(et).setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						result.confirm(et.getText().toString());
					}

				}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						result.cancel();
					}
				});

				// 屏蔽keycode等于84之类的按键，避免按键后导致对话框消息而页面无法再弹出对话框的问题
				builder.setOnKeyListener(new OnKeyListener() {
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						Log.v("onJsPrompt", "keyCode==" + keyCode + "event=" + event);
						return true;
					}
				});

				// 禁止响应按back键的事件
				// builder.setCancelable(false);
				AlertDialog dialog = builder.create();
				dialog.show();
			} catch (Exception e) {
				LogUtils.loge("wap on js alert : activity die ? ~");
			}
			return true;
			// return super.onJsPrompt(view, url, message, defaultValue,
			// result);
		}
	};

	private WebViewClient viewClient = new WebViewClient() {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// view.loadUrl(url);
			// return true;
			return false;
		}

		@Override
		public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {
		}

		@Override
		public void onPageFinished(WebView view, String url) {
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Check if the key event was the Back button and if there's history
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (webGoBack())
				return true;
		}
		// If it wasn't the Back key or there's no web page history, bubble up
		// to the default
		// system behavior (probably exit the activity)
		return super.onKeyDown(keyCode, event);
	}

	public OnClickListener onBackClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			startAnimation(view, AnimUtils.init().addAlpha(1f, 0.2f, 0, 200, new LinearInterpolator(), Animation.REVERSE).create());

			if (!webGoBack()) {
				finish();
			}
		}
	};

	private boolean webGoBack() {
		if (webView.canGoBack()) {
			webView.goBack();
			return true;
		}
		return false;
	}
}
